import { defineStore } from 'pinia'
import { ref } from 'vue'

export const usePlayerStore = defineStore('player', () => {

    /**
     *  设置变量
     */
    //当前播放的歌曲封面
    const cover = ref<string>('https://p1.music.126.net/T62FhTyq2Y-SY558NvME8g==/109951165498033031.jpg?param=200y110')
    // 播放列表
    const playList = ref<Array<musicItem>>([]);
    /**
     * 当前播放状态
     * ```js
     * playStatus = true;  // 播放状态
     * playStatus = false; // 暂停状态
     * ````
     */
    const playStatus = ref<boolean>(false);
    //当前播放的序号
    const currentMusicIndex = ref<number>(0);
    //网易云播放id?
    const currentId = ref<string>('0');
    //播放时间信息
    const currentTimeInfo = ref<playTime>({ total: 0, current: 0 })
    //历史播放列表
    const historyPlaylist = ref<any>()

    /**        
     * 设置播放时长
     * @param playTime  播放时间
     */

    function setTime(playTime: playTime): boolean {
        if (playTime.current > playTime.total) { return false; }
        currentTimeInfo.value.total = playTime.total;
        currentTimeInfo.value.current = playTime.current;
        return true;
    };
    //设置播放列表
    function setPlayList(musicList: musicItem[]) {
        playList.value = musicList;
    };
    //设置播放状态
    function setPlayState(state: any, isPlay: boolean) {
        state.playStatus = isPlay;
    };

    //添加元素
    function addMusic(item: musicItem) {
        playList.value = [...playList.value, item];
    };

    /**
     * 移除某元素
     * @param id 
     * @returns 成功返回true 失败返回false
     */
    function removeByid(id: number) {
        playList.value.forEach((item, index) => {
            if (item.id === id) {
                playList.value.splice(index, 1);
                return true;
            }
        })
        return false;
    }

    //设置播放序号
    function setPlayIndex(Index: number) {
        currentMusicIndex.value = Index;
    }

    //设置当前播放的ID
    function setCurrentId(state: any, id: string) {
        state.currentId = id;
    }
    //导出方法
    return { cover, historyPlaylist, playList, playStatus, currentMusicIndex, currentId, currentTimeInfo, addMusic, setTime, setPlayList, setPlayState, setPlayIndex, setCurrentId }
})

interface playTime {
    total: number,
    current: number
}
interface musicItem {
    cover: string;
    name: string;
    id: number;
    album: string;
    dt: number;
    singer: string,
}